﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BlackBird.DataAccess;
using BlackBird.Repositories;
using System.Security.Principal;
using System.Web.Mvc;

namespace BlackBird.ControllerHelpers
{
	public class AccountHelper
	{
		private const string UserSessionKey = "CurrentUser";
		private const string UserCookieUserIdKey = "CurrentUserId";

		/// <summary>
		/// Check the log in user info
		/// </summary>
		/// <param name="username"></param>
		/// <param name="password"></param>
		/// <param name="currentuser"></param>
		/// <returns></returns>
		public static bool ValidateUser(string username, string password,out user currentuser)
		{
			return AccountDataAccess.ValidateUser(username, password, out currentuser);
			//UserRepository userRepository = new UserRepository();
			//return userRepository.ValidateUser(username, password);
		}

		/// <summary>
		/// Add User info to Session and User Id to Cookie
		/// </summary>
		/// <param name="context"></param>
		/// <param name="currentuser"></param>
		public static void AddAccountInfo(Controller context,user currentuser)
		{
			context.Session[UserSessionKey] = currentuser.idUser;
			HttpCookie aCookie = new HttpCookie(UserCookieUserIdKey, currentuser.idUser);
			aCookie.Expires = DateTime.Now.AddDays(1);
			context.Response.Cookies.Add(aCookie);
		}

		/// <summary>
		/// Get Current User Detail Info
		/// </summary>
		/// <param name="ctrl"></param>
		/// <returns>user object that include detail info</returns>
		public static user GetCurrentUser(Controller ctrl)
		{
			string userId = ctrl.Session[UserSessionKey] as string;
			user currentUser = AccountDataAccess.GetUserInfoByUserID(userId);
			if (currentUser == null)
				throw new NullReferenceException("Failed to find current user info from Session");

			return currentUser;
		}

		/// <summary>
		/// Get Current User ID Info
		/// </summary>
		/// <param name="ctrl"></param>
		/// <returns>Just ID Info</returns>
		public static string GetCurrentUserId(Controller ctrl)
		{
			HttpCookie userId = ctrl.Request.Cookies[UserCookieUserIdKey];
			if(userId == null)
				throw new NullReferenceException("Failed to find current user id from cookie");

			return userId.Value;
		}
	}
}